#include "udpServer.hpp"
#include <memory>
#include <unordered_map>
#include <fstream>
using namespace Server;
static void Usage(string proc)
{
    cout << "\nUsage:\n\t" << proc << " local_port\n\n";
}
const string DictTxt = "./dict.txt";
unordered_map<string,string> dict;
static bool cutString(string& str,string& s1,string& s2,const string& sep)
{
    auto pos = str.find(sep);
    if(pos == string::npos)
        return false;
    s1 = str.substr(0,pos);
    s2 = str.substr(pos + sep.size());
    return true;
}
static void initDict()
{
    ifstream in(DictTxt,ios::binary);
    if(!in.is_open())
    {
        cerr << "open fail:" << DictTxt << "error" << endl;
        exit(OPEN_ERR);
    }
    string line;
    string key,value;
    while(getline(in,line))
    {
        if(cutString(line,key,value,":"))
        {
            dict.insert(make_pair(key,value));
        }
    }
    in.close();
    cout << "load dict success" << endl;
}
//翻译：
void TranslationWord(int sockfd,string clientIp,uint16_t clientPort,string message)
{
    string response_message;
    auto iter = dict.find(message);
    if(iter == dict.end()) 
        response_message = "unknown";
    else 
        response_message = iter->second;
 
    struct sockaddr_in client;
    bzero(&client, sizeof(client));
    client.sin_family = AF_INET;
    client.sin_port = htons(clientPort);
    client.sin_addr.s_addr = inet_addr(clientIp.c_str());
 
    sendto(sockfd, response_message.c_str(), response_message.size(), 0, (struct sockaddr*)&client, sizeof(client));
}
int main(int argc, char *argv[])
{
    if (argc != 2)
    {
        Usage(argv[0]);
        exit(USAGE_ERR);
    }
    //加载词库
    initDict();
    uint16_t port = atoi(argv[1]);
    unique_ptr<udpServer> usvr(new udpServer(TranslationWord,port));
    usvr->initServer();
    usvr->startServer();
    return 0;
}